# -*- coding: utf-8 -*-
# @Author: QX
# @File: YamlCaseParser.py
import copy
import os
import uuid

import yaml

from core.globalContext import g_context
from utils.VarRender import ReFresh

gc = g_context()
def Read_Yaml(filepath):
    case_infos=[]
    with open(filepath,'r',encoding='utf-8')  as f :
        yaml_data = yaml.safe_load(f)
        case_infos.append(yaml_data)
    return case_infos

# print(Read_Yaml('E:\Python_Project\Appium_Develop_01\Appium_Python\examples\yamldubug\context.yaml'))
# print("===================================")

# 加载所有的context中的内容到存储空间中
def load_context_from_yaml(filepath):
    try:
        yaml_file_path = os.path.join(filepath,'context.yaml')
        with open(yaml_file_path,'r',encoding='utf-8')  as f :
            yaml_data = yaml.safe_load(f)
        # print('加载context成功',yaml_data)
        if yaml_data:
            # 用 if yaml_data: 能确保只有在有数据的情况下才执行 gc.set_by_dict()。
            gc.set_by_dict(yaml_data)

    except Exception  as e:
        print('加载context文件失败')
    else:
        return (yaml_data)
# print(load_context_from_yaml('E:\Python_Project\Appium_Develop_01\Appium_Python\examples\yamldubug'))

'''读出某个目录满足数字开头，yaml为扩展名的所有文件，格式化为多个测试用例'''
def load_yaml_files(filepath):
    #定义一个列表变量装所有的测试用例
    yaml_caseinfos =[]
    #读出全局变量context.py
    load_context_from_yaml(filepath)
    #读出某个目录满足数字开头，yaml为扩展名的所有文件名，并且数据排序
    file_names = []
    sum_files = os.listdir(filepath)
    # print("sum_files",sum_files)
    file_names12 = []
    for f in sum_files:   #[(1,'A1_loupe_search.yaml'),(2,'A2_loupe_search.yaml')
        if f.endswith('.yaml')  and f.split("_")[0].isdigit():
            file_number = int(f.split('_')[0])
            file_names.append((file_number,f))
            file_names12.append(f)
    # print("file_names1===",file_names,"=====file-names12",file_names12)
    file_names.sort()
    file_names = [f[-1] for f in file_names]
    file_names12.sort()
    # print("sort_file_name12",file_names12)
    # print("file_names==",file_names)
    #读出所有满足条件的测试用例
    for filename  in file_names:
        file_path  = os.path.join(filepath,filename)
        with open(file_path,'r',encoding='utf-8')  as rfile:
            caseinfo = yaml.full_load(rfile)
            yaml_caseinfos.append(caseinfo)
    return (yaml_caseinfos)
#
# print("========load_yaml_files====================")
# print(load_yaml_files('E:\Python_Project\Appium_Develop_01\Appium_Python\examples\yaml_case_plat'))

def load_yaml_file1(filepath):
    yamls_caseinfos = []
    sum_files = os.listdir(filepath)
    file_names = []
    for f in sum_files:
        if f.endswith('.yaml') and f.split("_")[0].isdigit():
            file_names.append(f)
    file_names.sort()
    # print("file_names==load_yaml_file1",file_names)
    for file_name in file_names:
        # print(f"{file_name}=",file_name)
        file_name = os.path.join(filepath,file_name)
        with open(file_name,'r',encoding='utf-8') as rfile:
            caseinfo = yaml.full_load(rfile)
            yamls_caseinfos.append(caseinfo)
    return yamls_caseinfos
# print("========load_yaml_file1====================")
# print(load_yaml_file1('E:\Python_Project\Appium_Develop_01\Appium_Python\examples\yaml_case_plat'))


def yaml_case_parser(filepath):
    """
        返回指定条件的格式
        :param filepath:  文件的路径
        :return: {
                "case_infos": case_infos,  #  所有的测试用例 []
                "case_names": case_names   #  所有测试用例对应的标题 []
                }
    """
    case_infos = []
    case_names = []
    #获所有要测试的用例文件内容
    yaml_caseinfos = load_yaml_files(filepath)
    #一个用例一个用例查找是否有ddts
    for caseinfo  in yaml_caseinfos:
        ddts = caseinfo.get('ddts',[])
        if len(ddts)>0:
            caseinfo.pop("ddts")

        #测试用例的生成和标题生成
        if len(ddts)==0:
            #标题
            case_name = caseinfo.get('desc',uuid.uuid4().__str__())
            caseinfo.update({"_case_name":case_name})
            case_names.append(case_name)
            #测试用例
            case_infos.append(caseinfo)
        else:
            for ddt in ddts:
                #测试用例
                new_case = copy.deepcopy(caseinfo)
                # context = new_case.get("context",{})
                new_case.update({"context":ddt})
                case_infos.append(new_case)

                #测试用例的标题
                case_name = f'{caseinfo.get("desc",uuid.uuid4().__str__())}-{ddt.get("desc",uuid.uuid4().__str__())}'
                new_case.update({"_case_name":case_name})
                case_names.append(case_name)
    return{
        "case_infos": case_infos,  # 所有的测试用例 []
        "case_names": case_names  # 所有测试用例对应的标题 []
    }
def yaml_case_parser1(filepath):
    case_infos = []
    case_names = []
    yaml_caseinfos = load_yaml_file1(filepath)
    for caseinfo in yaml_caseinfos:
        ddts = caseinfo.get('ddts', [])
        if len(ddts) > 0:
            caseinfo.pop("ddts")
        if len(ddts) == 0:
            case_name = caseinfo.get('desc', uuid.uuid4().__str__())
            caseinfo.update({"_case_name": case_name})
            case_names.append(case_name)
            case_infos.append(caseinfo)
        else:
            for ddt in ddts:
                new_case = copy.deepcopy(caseinfo)
                new_case.update({"context": ddt})
                case_infos.append(new_case)
                case_name = f'{caseinfo.get("desc", uuid.uuid4().__str__())}-{ddt.get("desc", uuid.uuid4().__str__())}'
                new_case.update({"_case_name": case_name})
                case_names.append(case_name)
    return {
        "case_infos": case_infos,
        "case_names": case_names
    }



# print("\n\n========yaml_case_parser====================")
# case_infos = yaml_case_parser1('E:\Python_Project\Appium_Develop_01\Appium_Python\examples\yamldubug')
# print("case_infos",case_infos['case_infos'][0])
# print("desc",case_infos['case_infos'][0]['desc'])
# for case_info in case_infos:
#     print(case_infos[case_info])


# if __name__ == '__main__':
#     # filepath = r'E:\Python_Project\Appium_Develop_01\Appium_Python\examples\yamldubug'
#     # # 测试用例的数据准备
#     # caseinfo = yaml_case_parser(filepath)
#     # print(caseinfo)
#
#     filepath1 = r"E:\Python_Project\Appium_Develop_01\Appium_Python\examples\yamldubug\context.yaml"
#     caseinfo = Read_Yaml(filepath1)
#     print(caseinfo)


